package com.example.jay.myapplication;

import android.os.Environment;
import android.widget.Toast;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

public class FilesHandler {

    //存放每条合理数据的list
    private static List<LocationResult> resultList;
    //存放设备名称的list
    private static List<String> devicesList;
    //使用HashSet自动去重，直接获得实际的设备mac
    private static HashSet<String> devicesSet;
    private static Map<String, Double> resultMap;

    private static String path;

    public static void handleTxt(String targetPath) throws IOException {
        createFile();
        String getContent = readFile(targetPath);
        resultMap = new HashMap<>();
        resultList = new ArrayList<>();
        devicesSet = new HashSet<>();
        devicesList = new ArrayList<>();
        txtHandler(getContent);
        devicesList.addAll(devicesSet);
        System.out.println(targetPath + "结果如下：");
        writeContent(targetPath + "文件的处理的结果是:");
        for (int j = 0; j < devicesList.size(); j++) {
            int sum = 0, time = 0;
            double ans, variance, varianceSum = 0;
            for (int k = 0; k < resultList.size(); k++) {
                if (devicesList.get(j).equals(resultList.get(k).getMac())) {
                    sum = sum + resultList.get(k).getRssi();
                    time++;
                }
            }
            //求得平均值
            ans = (double)sum / (double) time;
            for (int k = 0; k < resultList.size(); k++) {
                varianceSum = varianceSum + Math.pow((ans - resultList.get(k).getRssi()), 2);
            }
            variance = varianceSum / time;
            String result = "mac: " + devicesList.get(j) + ", avg: " + ans;
            writeContent(result);
            System.out.println("设备 " + devicesList.get(j) + "的平均RSSI值为：" + ans + ",出现了" + time+
                    "次" + "和为" + sum + ", 方差为：" + variance);
            resultMap.put(devicesList.get(j), ans);
        }

    }

    /**
     * 对文本中的内容进行处理
     * @param content 文本内容
     */
    private static void txtHandler(String content) {
        String strContent[] = content.split("\n");
        for (int i = 0; i < strContent.length; i++) {
            String details[] = strContent[i].split(",");
            //System.out.println(Arrays.toString(details));
            String name = details[0];
            String mac = details[1].substring(4, details[1].length());
            int rssi = Integer.parseInt(details[2].substring(5, details[2].length()));
            if (!name.equals("null") && rssi > -100) {
                resultList.add(new LocationResult(name, rssi, mac));
                devicesSet.add(mac);
            }
        }
    }

    /**
     * 读取文件内容的方法
     * @param filePath txt文件的路径
     * @return 将文件中所有内容以String方式取得
     */
    private static String readFile(String filePath){
        StringBuilder builder = new StringBuilder();
        try {
            String encoding="UTF-8";
            File file=new File(filePath);
            if(file.isFile() && file.exists()){ //判断文件是否存在
                InputStreamReader read = new InputStreamReader(new FileInputStream(file),encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt;
                while((lineTxt = bufferedReader.readLine()) != null){
                    lineTxt = lineTxt + "\n";
                    builder.append(lineTxt);
                }
                read.close();
            }else{
                System.out.println("找不到指定的文件");
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
        }
        return builder.toString();
    }

    /**
     * 创建一个txt文件并向其中写入得到的平均值结果
     */
    private static void createFile(){
        File sdCardDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "bluetooth_analyze");
        if (!sdCardDir.exists()) {
            if (!sdCardDir.mkdirs()) {
                try {
                    sdCardDir.createNewFile();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        try {
            //新建文件
            String fileName = getTime() + "_analyze_log.txt";
            File saveFile = new File(sdCardDir, fileName);
            path = sdCardDir.getAbsolutePath();
            if (!saveFile.exists()) {
                saveFile.createNewFile();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeContent(String content) {
        FileWriter writer = null;
        String lastPath = path+"/"+getTime()+"_analyze_log.txt";
        try {
            writer = new FileWriter(lastPath, true);
            writer.write(content + "\r\n");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(writer != null){
                    writer.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String getTime() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");// HH:mm:ss
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }
}
